/*
 * Copyright (c) 2011 Anthony Vandikas
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, 
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 
 * is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE 
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "stdafx.h"
#include "InventoryWidget.h"

#include "AbstractInventory.h"
#include "InventoryModel.h"

InventoryWidget::InventoryWidget(AbstractInventory &inventory)
	: inventory(&inventory), model(new InventoryModel(inventory))
{
	ui.setupUi(this);
	ui.itemView->setModel(model);
}

InventoryWidget::~InventoryWidget()
{
	delete model;
}

void InventoryWidget::addItems()
{
	QList<Item> items;
	auto name = ui.itemBox->text();
	for (int i = ui.fromBox->value(); i <= ui.toBox->value(); i++)
		items << Item(name, i);

	inventory->addItems(items);
}

void InventoryWidget::removeItems()
{
	// No point deleting anything if nothing is selected.
	// Also, prevent the user from 'accidentally' deleting stuff.
	if (ui.itemView->selectionModel()->selectedIndexes().count() == 0 ||
		QMessageBox::question(this, "InventoryMan", "Are you sure you want to delete the selected items?", QMessageBox::Yes, QMessageBox::No) != QMessageBox::Yes)
		return;

	QList<Item> items;
	foreach (auto index, ui.itemView->selectionModel()->selectedIndexes())
		items << model->getItem(index);

	inventory->removeItems(items);
}

void InventoryWidget::fromValueChanged() 
{
	// Prevent the item index bounds from ovelapping.
	// The user shouldn't be able to 'add French Horns #4 to #1'.
	if (ui.fromBox->value() > ui.toBox->value())
		ui.toBox->setValue(ui.fromBox->value());
}

void InventoryWidget::toValueChanged()
{
	if (ui.toBox->value() < ui.fromBox->value())
		ui.fromBox->setValue(ui.toBox->value());
}
